package com.ruoyi.web.controller.ma;


import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.json.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.ma.domain.ShellUser;
import com.ruoyi.ma.domain.WebhookGitee;
import com.ruoyi.ma.domain.WebhookGiteeRecord;
import com.ruoyi.ma.service.IWebhookGiteeService;
import com.sun.deploy.net.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/webhook")
public class WebHooksController extends BaseController {

    @Autowired
    private IWebhookGiteeService webhookGiteeService;


    @PostMapping("/gitee")
    @ResponseBody
    public AjaxResult gitee(@RequestBody JSONObject jsonObject) {
        HttpServletRequest request = ServletUtils.getRequest();
        //获取请求头信息
        Enumeration headerNames = request.getHeaderNames();
        // 第一版本没有设置密码，暂时不做验证
        WebhookGiteeRecord webhookGiteeRecord = new WebhookGiteeRecord();
        String giteeToken = "";
        String hookEvent = "";
        Long pushTime = 0L;
        //使用循环遍历请求头，并通过getHeader()方法获取一个指定名称的头字段
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            switch (headerName) {
                case "x-gitee-token":
                    giteeToken = request.getHeader(headerName);
                    webhookGiteeRecord.setToken(giteeToken);
                    break;
                case "x-gitee-event":
                    hookEvent = request.getHeader(headerName);
                    webhookGiteeRecord.setRequestType(hookEvent);
                    break;
                case "x-gitee-timestamp":
                    pushTime = Long.parseLong(request.getHeader(headerName));
                    webhookGiteeRecord.setRequestTime(new Date(pushTime));
                    break;
                default:
                    break;
            }
        }
        Boolean bl = webhookGiteeService.hook(webhookGiteeRecord, jsonObject);
        if (bl) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

}
